package com.agileai.portal.controller.bar;

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.common.KeyValuePair;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.StandardEditHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.bar.ExtGeneralQueryConfigManage;
import com.agileai.util.StringUtil;

public class ExtGeneralQueryConfigManageEditHandler
        extends StandardEditHandler {
    public ExtGeneralQueryConfigManageEditHandler() {
        super();
        this.listHandlerClass = ExtGeneralQueryConfigManageListHandler.class;
        this.serviceId = buildServiceId(ExtGeneralQueryConfigManage.class);
    }

    protected void processPageAttributes(DataParam param) {
        setAttribute("FIELD_TYPE",
                     FormSelectFactory.create("EXT_FIELD_TYPE")
                                      .addSelectedValue(getOperaAttributeValue("FIELD_TYPE",
                                                                               "TEXT")));
        setAttribute("TRIGER_CASCADE",
                     FormSelectFactory.create("BOOL_DEFINE")
                                      .addSelectedValue(getOperaAttributeValue("TRIGER_CASCADE",
                                                                               "N")));
        setAttribute("BREAK_LINE",
                     FormSelectFactory.create("BOOL_DEFINE")
                                      .addSelectedValue(getOperaAttributeValue("BREAK_LINE",
                                                                               "N")));
        setAttribute("IMMEDIATE_TRIGGER",
                FormSelectFactory.create("BOOL_DEFINE")
                                 .addSelectedValue(getOperaAttributeValue("IMMEDIATE_TRIGGER",
                                                                          "N")));
        setAttribute("PAGE_CODE",getOperaAttributeValue("PAGE_CODE",param.get("pageId")));
        setAttribute("PORTLET_CODE",getOperaAttributeValue("PORTLET_CODE",param.get("portletId")));
        setAttribute("DISPLAY_LENGTH",getOperaAttributeValue("DISPLAY_LENGTH","100"));
        setAttribute("SORT_NO",getOperaAttributeValue("SORT_NO","1"));
    }
    @PageAction
    public ViewRenderer retrieveDefaultValues(DataParam param){
    	String responseText = "";
    	DataRow row = this.getService().getRecord(param);
    	if (row != null && row.size() > 0){
    		String fieldType = row.getString("FIELD_TYPE");
    		String defaultValues = row.getString("DEFAULT_VALUES");
    		FormSelect defaultValuesSelect = this.buildDefaultSelect(fieldType, defaultValues);
    		responseText = defaultValuesSelect.getScriptSyntax("defaultValues");
    	}
    	return new AjaxRenderer(responseText);
    }
    @PageAction
    public ViewRenderer addDefaultValue(DataParam param){
    	String responseText = "";
    	String id = param.get("ID");
    	DataRow row = this.getService().getRecord(param);
		String fieldType = row.getString("FIELD_TYPE");
		String defaultCode = param.get("defaultCode");
		String defaultValue = param.get("defaultValue");
		if(fieldType.equals("SELECT")||fieldType.equals("CHECKBOX")){
			String defaultValues = row.getString("DEFAULT_VALUES");
			try {
				JSONArray jsonArray = null;
				if (StringUtil.isNullOrEmpty(defaultValues)){
					jsonArray = new JSONArray();
				}else{
					jsonArray = new JSONArray(defaultValues);
				}
	    		JSONObject jsonObject = new JSONObject();
	    		jsonObject.put("code", defaultCode);
	    		jsonObject.put("value",defaultValue);
	    		jsonArray.put(jsonObject);
	    		String jsonArrayValue = jsonArray.toString();
	    		this.getService().saveDefaultValues(id, jsonArrayValue);
	    		
	    		FormSelect defaultValuesSelect = this.buildDefaultSelect(fieldType, jsonArrayValue);
	    		responseText = defaultValuesSelect.getScriptSyntax("defaultValues");    		
			} catch (Exception e) {
				log.error(e.getLocalizedMessage(), e);
			}
		}else{
			this.getService().saveDefaultValues(id, defaultValue);
    		FormSelect defaultValuesSelect = this.buildDefaultSelect(fieldType, defaultValue);
    		responseText = defaultValuesSelect.getScriptSyntax("defaultValues");    
		}
    	return new AjaxRenderer(responseText);
    }
    @PageAction
    public ViewRenderer delDefaultValue(DataParam param){
    	String responseText = "";
    	String id = param.get("ID");
    	DataRow row = this.getService().getRecord(param);
		String fieldType = row.getString("FIELD_TYPE");
		if(fieldType.equals("SELECT")||fieldType.equals("CHECKBOX")){
			String defaultValues = row.getString("DEFAULT_VALUES");
			String defaultValue = param.get("defaultValues");
			List<KeyValuePair> defalutValueList = new ArrayList<KeyValuePair>();
			try {
				JSONArray jsonArray = null;
				if (StringUtil.isNullOrEmpty(defaultValues)){
					jsonArray = new JSONArray();
				}else{
					jsonArray = new JSONArray(defaultValues);
				}
	    		for (int i=0;i < jsonArray.length();i++){
	    			JSONObject jsonObject = jsonArray.getJSONObject(i);
	    			String key = jsonObject.getString("code");
	    			if (defaultValue.equals(key)){
	    				continue;
	    			}
	    			String value = jsonObject.getString("value");
	    			KeyValuePair keyValuePair = new KeyValuePair();
	    			keyValuePair.setKey(key);
	    			keyValuePair.setValue(value);
	    			defalutValueList.add(keyValuePair);
	    		}
	    		JSONArray newJsonArray = this.listToRelInfoJson(defalutValueList);
	    		String jsonArrayValue = newJsonArray.toString();
	    		this.getService().saveDefaultValues(id, jsonArrayValue);
	    		
	    		FormSelect defaultValuesSelect = this.buildDefaultSelect(fieldType, jsonArrayValue);
	    		responseText = defaultValuesSelect.getScriptSyntax("defaultValues");    		
			} catch (Exception e) {
				log.error(e.getLocalizedMessage(), e);
			}
		}else{
			this.getService().saveDefaultValues(id, "");
    		FormSelect defaultValuesSelect = this.buildDefaultSelect(fieldType, "");
    		responseText = defaultValuesSelect.getScriptSyntax("defaultValues");   
		}
    	return new AjaxRenderer(responseText);
    }
    
    private FormSelect buildDefaultSelect(String fieldType,String defaultValues) {
        FormSelect formSelect = new FormSelect();
        if(fieldType.equals("SELECT")||fieldType.equals("CHECKBOX")){
        	try {
        		JSONArray jsonArray = new JSONArray(defaultValues);
        		for (int i=0;i < jsonArray.length();i++){
        			JSONObject jsonObject = jsonArray.getJSONObject(i);
        			String key = jsonObject.getString("code");
        			String value = jsonObject.getString("value");
        			formSelect.addValue(key, value);
        		}
			} catch (Exception e) {
				log.error(e.getLocalizedMessage(),e);
			}
        }else{
        	formSelect.addValue("text", defaultValues);
        }
        formSelect.addHasBlankValue(false);
        return formSelect;
    }

    protected ExtGeneralQueryConfigManage getService() {
        return (ExtGeneralQueryConfigManage) this.lookupService(this.getServiceId());
    }
    
    private JSONArray listToRelInfoJson(List<KeyValuePair> defalutValueList){
    	JSONArray result = new JSONArray();
    	try {
        	for (int i=0;i < defalutValueList.size();i++){
        		KeyValuePair infoId = defalutValueList.get(i);
        		JSONObject jsonObject = new JSONObject();
        		jsonObject.put("code", infoId.getKey());
        		jsonObject.put("value", infoId.getValue());
        		result.put(jsonObject);
        	}			
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return result;
    }
}